$(function () {
	initMenu();//从数据库读取时取消注释
	//getDefault();
	//initLocationHash();
	showDate();
	$(".colour div").removeClass("selected");
    $(".colour").find("li[rel="+ths.getTheme()+"]").children().first().addClass("selected");
    $(".colour li").click(function () {
        $(".colour div").removeClass("selected");
        $(this).children().first().addClass("selected");
        changeTheme($(this).attr("rel"));
    });
	//绑定tabs的右键菜单
	$("#mainTabs").tabs({
		onContextMenu : function (e, title) {
			e.preventDefault();
			$('#tabsMenu').menu('show', {
				left : e.pageX,
				top : e.pageY
			}).data("tabTitle", title);
		},
		onSelect:function(title, index){
			//setLocationHash();
		},
		onClose:function(title,index){
			//setLocationHash();
		}
	});
	
	//实例化menu的onClick事件
	$("#tabsMenu").menu({
		onClick : function (item) {
			var curTabTitle = $(this).data("tabTitle");
			if(item.id=="mm-tabupdate"){
				var currTab = $('#mainTabs').tabs('getSelected');
		        var url = $(currTab.panel('options').content).attr('src');
		        $('#mainTabs').tabs('update', {
		            tab: currTab,
		            options: {
		                content: createFrame(url)
		            }
		        });
			}else if(item.id=="mm-tabclose"){
				var tab=$('#mainTabs').tabs("getTab",curTabTitle);
				if(tab.panel('options').closable){
					$('#mainTabs').tabs('close', curTabTitle);
				}
			}else if(item.id=='mm-tabcloseall'){
				var len=$('#mainTabs').tabs("tabs").length;
				for(i=len-1;i>-1;i--){
					var tab= $('#mainTabs').tabs('getTab',i);
					if(tab.panel('options').closable){
						$('#mainTabs').tabs('close', i);
					}
				}
			}else if(item.id=='mm-tabcloseother'){
				var currTab= $('#mainTabs').tabs('getSelected')
				var tabs=$.grep($('#mainTabs').tabs('tabs'), function(tab,i){
					  	return tab!= currTab&&tab.panel('options').closable;
					});
				$.each(tabs,function (i, tab) {
					$('#mainTabs').tabs('close', $(this).panel("options").title);
				});
			}else if(item.id=='mm-tabcloseright'){
				var currTab= $('#mainTabs').tabs('getSelected')
				var len=$('#mainTabs').tabs("tabs").length;
				var index= $('#mainTabs').tabs('getTabIndex',currTab);
				for(var i=len-1;i>index;i--){
					var tab= $('#mainTabs').tabs('getTab',i);
					if(tab.panel('options').closable){
						$('#mainTabs').tabs('close', i);
					}
				}
			}else if(item.id=='mm-tabcloseleft'){
				var currTab= $('#mainTabs').tabs('getSelected')
				var index= $('#mainTabs').tabs('getTabIndex',currTab);
				for(var i=index-1;i>-1;i--){
					var tab= $('#mainTabs').tabs('getTab',i);
					if(tab.panel('options').closable){
						$('#mainTabs').tabs('close', i);
					}
				}
			}
		}
	});
	if ($('#calendar').length > 0) {
        $('#calendar').calendar({
            fit: true,
            current: new Date(),
            border: false,
            onSelect: function (date) {
                $(this).calendar('moveTo', new Date());
            }
        });
    }
	if ($('#onlineUser').length > 0) {
        $('#onlineUser').datagrid({
            url: ths.getContextPath()  + '/platform/home/getOnlineUser',
            fit: true,
            fitColumns: true,
            pagination: true,
            pageSize: 10,
            pageList: [10],
            nowarp: false,
            border: false,
            idField: 'userId',
            sortName: 'loginTime',
            sortOrder: 'desc',
            singleSelect: true,
            remoteSort: true,
            columns: [[{
                title: '登录名',
                field: 'userName',
                width: 80,
                sortable: false
            }, {
                title: '真实姓名',
                field: 'realName',
                width: 100,
                sortable: false
            }, {
                title: '登录时间',
                field: 'loginTime',
                width: 200,
                sortable: false
            }]],
            onClickRow: function (rowIndex, rowData) {
            },
            onLoadSuccess: function (data) {
                $('#onlinePanel').panel('setTitle', data.total + '人在线');
            }
        }).datagrid('getPager').pagination({
            showPageList: false,
            showRefresh: true,
            beforePageText: '',
            afterPageText: '/{pages}',
            displayMsg: ''
        });
    }	 
});
/**
 * 获得默认主题
 */
function getDefault(){
	$.ajax({
		url:"platSettingService/getPersonTheme.json",
		type:"post",
		dataType:"text",
		success:function(data){
			$(".colour div").removeClass("selected");
		    $(".colour").find("li[rel="+data+"]").children().first().addClass("selected");
		        changeTheme(data);
		}
	});
}

/**
 * 改变主题
 * @param themeName 主题名称
 * @author heyj
*/
function changeTheme(themeName){
	var themes = $('#themes');
    var href = themes.attr('href');
    href = href.substring(0, href.indexOf('themes')) + 'themes/' + themeName + '/easyui.css';
    themes.attr('href', href);

    var $iframe = $('iframe');
    if ($iframe.length > 0) {
        for (var i = 0; i < $iframe.length; i++) {
            var ifr = $iframe[i];
            $(ifr).contents().find('#themes').attr('href', href);
        }
    }
    //提交后台
//    $.post("/changeTheme.run", { theme: themeName }, function (data) {
//        if (data.Success) {
//            //showMessage("info", "主题应用成功！");
//        }
//    });
}

/**
 * 显示时间
 * @author heyj
 * @since 2014.06.03
*/
function showDate(){
	$("#bgclock").html(getTime());
	var timer = setInterval(function () { $("#bgclock").html(getTime()); }, 200);
}

function initLocationHash() {
    var subUrl = location.hash.replace('#!', '');
    /*$.ajax({
		url:"resourceService/queryResourceList.json",
		type:"post",
		dataType:"json",
		success:function(data){
		    $.each(data, function (i,n) {
		    	if(n.url!=null){
			        var s = n.url.replace('.jsp', '');
			        if (n.url && n.url != '#' && (subUrl == s || subUrl.indexOf(s) > -1))
			        	openTab(n.text, subUrl + '.jsp', null);
			    	}
		    });
		}
	});*/
};

function setLocationHash(){
	try {
        var $obj = $('#mainTabs');
        var src = '', tabs = $obj.data().tabs.tabs;
        var tab = $obj.tabs('getSelected');

        var fnSrc = function (tab) {
            var iframe = tab.find('iframe');
            return iframe.length ? iframe[0].src.replace(location.host, '').replace('http://', '').replace('.jsp', '') : '';
        };

        if (tab) {
            src = fnSrc(tab);
            if (src) window.location.hash = '!' + src;   //如果src没有，就不设置，case在f5刷新时出现
            if (src == homeUrl) window.location.hash = '';
        }
        else {
            src = fnSrc(tabs[tabs.length - 1]); //关闭tabs时，当前tab为空
            window.location.hash = '!' + src;
        }
    }
    catch (e) { }
}

/**
 * 初始化菜单
 * @author heyj
 * @since 2014.05.28
*/
function initMenu() {
	$("#leftMenu").html('<div id="topMenu" data-options="border:false,fit:true" class="easyui-accordion" ></div>');
	$.parser.parse($("#leftMenu"));	
	$.ajax({
		url:ths.system.contextPath + '/platform/menu/getMenuList',
		type:"post",
		dataType:"json",
		success:function(data){
			if(data.length == 0){
				return;
			}
			$.each(data, function(index, item){
				//生成手风琴
				$('#topMenu').accordion('add', {
					title : item.text,
					id : item.id,
					content: "<ul id='tree-" + item.id + "'></ul>",
					iconCls : item.iconCls||'icon-menu01',
					selected : index == 0 ? true : false
				});
				//生成菜单树
				if(!item.children || item.children.length == 0){
					return true;
				}
				$('#tree-' + item.id).tree({
					data : item.children,
					animate : true,
					checkbox : false,
					dataType : "json",
					onClick : function(node) {
						if (node.attributes != "") {
							var nodeUrl = node.attributes;
							if(null != nodeUrl && "" != nodeUrl){
								nodeUrl = addParamToUrl(ths.system.contextPath + nodeUrl, "moduleId", node.id);
								openTab(node.text,nodeUrl);
							}
						}
					}
				});
			});
		}
	});
}

/**
 * 刷新主框架的当前标签页
 * @author heyj
 * @since 2014.05.28
*/
function reloadTab() {
    var index_tabs = $('#mainTabs');
    var href = index_tabs.tabs('getSelected').panel('options').href;
    if (href) {/*说明tab是以href方式引入的目标页面*/
        var index = index_tabs.tabs('getTabIndex', index_tabs.tabs('getSelected'));
        index_tabs.tabs('getTab', index).panel('refresh');
    } else {/*说明tab是以content方式引入的目标页面*/
        var panel = index_tabs.tabs('getSelected').panel('panel');
        var frame = panel.find('iframe');
        try {
            if (frame.length > 0) {
                for (var i = 0; i < frame.length; i++) {
                    frame[i].contentWindow.document.write('');
                    frame[i].contentWindow.close();
                    frame[i].src = frame[i].src;
                }
                if (navigator.userAgent.indexOf("MSIE") > 0) {// IE特有回收内存方法
                    try {
                        CollectGarbage();
                    } catch (e) {
                    }
                }
            }
        } catch (e) {
        }
    }
}
/**
 * 移除主框架当前标签页
 * @author heyj
 * @since 2014.05.28
*/
function removeTab() {
    var index_tabs = $('#mainTabs');
    var index = index_tabs.tabs('getTabIndex', index_tabs.tabs('getSelected'));
    var tab = index_tabs.tabs('getTab', index);
    if (tab.panel('options').closable) {
        index_tabs.tabs('close', index);
    } else {
        showMessage('error', '[' + tab.panel('options').title + ']不可以被关闭！');
    }
}
/**
 * 缩放当前标签页，用于最大化
 * @author heyj
 * @obj 当前对象
 * @since 2014.05.28
*/
function resizeTab(obj) {
    if ($(obj).linkbutton("options").iconCls.toLowerCase() == 'icon-arrow-out') {
        $('#wrap').layout('hidden', 'all');
        $('#wrap').layout("panel", "center").panel("maximize");
        $(obj).linkbutton({
            iconCls: 'icon-arrow-in'
        });
    }
    else {
        $('#wrap').layout('show', 'all');
        $('#wrap').layout("panel", "center").panel("restore");
        $(obj).linkbutton({
            iconCls: 'icon-arrow-out'
        });
    }
}

/**
 * 获取本地时钟
 * @returns 返回日期时间
 * @author heyj
 * @since 2014.06.03
*/
function getTime() {
    var now = new Date();
    var year = now.getFullYear(); // getFullYear getYear
    var month = now.getMonth();
    var date = now.getDate();
    var day = now.getDay();
    var hour = now.getHours();
    var minu = now.getMinutes();
    var sec = now.getSeconds();
    var week;
    month = month + 1;
    if (month < 10)
        month = "0" + month;
    if (date < 10)
        date = "0" + date;
    if (hour < 10)
        hour = "0" + hour;
    if (minu < 10)
        minu = "0" + minu;
    if (sec < 10)
        sec = "0" + sec;
    var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
    week = arr_week[day];
    var time = "";
    //time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;
    time = year + "年" + month + "月" + date + "日" + " " + week;
    return time;
}

function loginOut(){
	showMessage('confirm', '是否确定退出登录?', function (confirm) {
        if (confirm) {
        	window.location = ths.system.contextPath + "/platform/home/loginOut";
        }
    });
}

/**
 * 修改密码
 */
function changePwd(){
	openInTopWindow({
        id: 'changePwdWin',
        src: ths.system.contextPath + "/platform/user/changePwd",
        destroy: true,
        title: "修改密码",
        iconCls: 'icon-save',
        width: 350,
        height: 200,
        modal: true,
        onLoad: function () {
            this.openerWindow = window;
            if (typeof this._init == 'function') {
                this._init();// 存在初始化方法则调用
            }
        }
    });
}

/**
 * 锁定窗口
 */
function lockWin(){
	openInTopWindow({
        id: 'unlockWin',
        src: ths.system.contextPath + "/platform/user/unlock",
        destroy: true,
        title: "解锁登录",
        iconCls: 'icon-save',
        closable : false,
        width: 350,
        height: 200,
        modal: true,
        onLoad: function () {
            this.openerWindow = window;
            if (typeof this._init == 'function') {
                this._init();// 存在初始化方法则调用
            }
        }
    });
}

/**
 * 消息通知
 */
$(function() {
	/*ths.notification.notify(60000, function(data) {
		if (utils.startsWith(data.url.toLowerCase(), "http")) {
			//绝对路径
			openTab(data.title, data.url);
		} else {
			//相对路径
			openTab(data.title, ths.getFullPath(data.url));
		}
	});*/
});
